package com.chen.authority.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.authority.common.constant.SysConstant;
import com.chen.authority.common.response.Response;
import com.chen.authority.common.response.SingleResponse;
import com.chen.authority.common.util.FileUtil;
import com.chen.authority.common.util.MinioUtil;
import com.chen.authority.common.util.SaTokenUtil;
import com.chen.authority.mapper.UserMapper;
import com.chen.authority.model.dto.UpdatePwdDto;
import com.chen.authority.model.dto.UserInfoDto;
import com.chen.authority.model.po.UserPo;
import com.chen.authority.model.vo.UserVo;
import com.chen.authority.service.FileService;
import com.chen.authority.service.UserCenterService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@RequiredArgsConstructor
public class UserCenterServiceImpl implements UserCenterService {

    private final UserMapper userMapper;
    private final FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateUserAvatar(MultipartFile file) {
        if (FileUtil.isNotImage(file)) {
            return Response.fail("文件为空，或类型不为图像");
        }
        String url = MinioUtil.uploadFile(file);
        boolean result = fileService.saveUploadFileInfo(file.getOriginalFilename(), file.getSize(), url, "用户头像");
        if (result) {
            userMapper.update(null, Wrappers
                    .<UserPo>lambdaUpdate()
                    .eq(UserPo::getId, StpUtil.getLoginId())
                    .set(UserPo::getImgUrl, url));
            UserVo user = SaTokenUtil.getLoginUser();
            user.setImgUrl(url);
            SaTokenUtil.setLoginUser(user);
            return SingleResponse.success(url);
        }
        return Response.fail();
    }

    @Override
    public Response updateUserPwd(UpdatePwdDto dto) {
        UserVo user = SaTokenUtil.getLoginUser();
        if (!SaSecureUtil.md5(dto.getOldPwd()).equals(user.getPassword())) {
            return Response.fail("原密码错误");
        }
        String newPwd = SaSecureUtil.md5(dto.getNewPwd());
        userMapper.update(null, Wrappers
                .<UserPo>lambdaUpdate()
                .eq(UserPo::getId, user.getId())
                .set(UserPo::getPassword, newPwd));
        user.setPassword(newPwd);
        StpUtil.getTokenSession().set(SysConstant.LOGIN_USER, user);
        return Response.success();
    }

    @Override
    public Response updateUserInfo(UserInfoDto dto) {
        boolean exists = userMapper.exists(Wrappers
                .<UserPo>lambdaQuery()
                .eq(UserPo::getEmail, dto.getEmail())
                .or()
                .eq(UserPo::getPhoneNumber, dto.getPhoneNumber()));
        if (exists) {
            return Response.fail("邮箱或手机号重复");
        }
        userMapper.updateById(dto.toPo(UserPo.class));
        UserVo user = SaTokenUtil.getLoginUser();
        BeanUtils.copyProperties(dto, user);
        StpUtil.getTokenSession().set(SysConstant.LOGIN_USER, user);
        return Response.success();
    }

}
